import { Injectable } from '@nestjs/common'
import { CoreCacheService, CoreCacheServiceOption } from '../core-cache.service'

@Injectable()
export class CoreCacheMemoryService extends CoreCacheService {
  readonly map = new Map<string, string>()

  readonly objMap = new Map<string, object>()

  constructor(option?: CoreCacheServiceOption) {
    super(option)
  }

  get(key: string): Promise<string | null> {
    return Promise.resolve(this.map.get(this.makeKey(key)))
  }

  set(key: string, data: string): Promise<void> {
    this.map.set(this.makeKey(key), data)
    return Promise.resolve()
  }

  del(key: string): Promise<void> {
    this.map.delete(this.makeKey(key))
    return Promise.resolve()
  }

  destroy(): Promise<void> {
    super.destroy()
    return this.clear()
  }

  clear(): Promise<void> {
    this.map.clear()
    this.objMap.clear()
    return Promise.resolve()
  }

  has(key: string): Promise<boolean> {
    return Promise.resolve(this.map.has(this.makeKey(key)))
  }

  createNSService(namespace: string): CoreCacheService {
    return new CoreCacheMemoryService({ namespace })
  }

  setObj<T extends object>(key: string, data: T): Promise<void> {
    this.objMap.set(this.makeKey(key), data)
    return Promise.resolve()
  }

  getObj<T extends object>(key: string): Promise<T> {
    return Promise.resolve(this.objMap.get(this.makeKey(key)) as T | null)
  }
}
